package com.inspur.cloud.security;

import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.enums.RoleEnum;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class AuthorizationHelper {
    /**
     * 返回当前登录人名称
     */
    public static String getAuthenticatedName() {
        return getAuthenticatedName(null);
    }

    /**
     * 返回当前登录人名称 带默认名称的
     */
    public static String getAuthenticatedName(String defaultUsername) {
        SecurityContext securityContext = SecurityContextHolder.getContext();

        Authentication auth = securityContext.getAuthentication();

        return (null == auth) ? defaultUsername : auth.getName();
    }

    /**
     * 返回当前登录人角色
     */
    public static String getAuthenticatedRole() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication auth = securityContext.getAuthentication();
        for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
            return grantedAuthority.getAuthority();
        }
        return "0";
    }

    /**
     * 返回当前登录人角色
     */
    public static UserEntity getUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        ApiAuthentication auth = (ApiAuthentication) securityContext.getAuthentication();
        if (auth == null) {
            return null;
        }
        return (UserEntity) auth.getDetails();
    }

    /**
     * 是管理员
     *
     * @return
     */
    public static boolean isAdmin() {
        UserEntity user = getUser();
        return isAdmin(user);
    }

    /**
     * 是管理员
     *
     * @return
     */
    public static boolean isAdmin(UserEntity user) {
        return checkRole(user, RoleEnum.Admin.getValue());
    }

    /**
     * 是租户
     *
     * @return
     */
    public static boolean isTenant() {
        UserEntity user = getUser();
        return isTenant(user);
    }

    public static boolean isUser() {
        UserEntity user = getUser();
        return isUser(user);
    }

    public static boolean isUser(UserEntity user) {
        return checkRole(user,RoleEnum.User.getValue());
    }

    /**
     * 是租户
     *
     * @return
     */
    public static boolean isTenant(UserEntity user) {
        return checkRole(user, RoleEnum.Tenant.getValue());
    }

    /**
     * 校验角色
     *
     * @return
     */
    private static boolean checkRole(UserEntity user, Integer role) {
        return user != null && user.getRole() != null && role.equals(user.getRole());
    }
}
